/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.UploadedFile;
import ui.common.AbstractUIBean;

/**
 *
 * @author Neo
 */
public class FileUpload extends AbstractUIBean {

  static String app_domain;

    public  String processFile(UploadedFile uploadFile) throws IOException {
        FileOutputStream fos = null;
        try {
            ExternalContext exContext = (ExternalContext) FacesContext.getCurrentInstance().getExternalContext();
            String absPath = uploadFile.getFileName();
            int exStart = absPath.lastIndexOf(".");
            String extension = absPath.substring(exStart);
            String gen = RandomGenerator.randomString(20);
            String path = exContext.getRealPath("/").replace("\\", "/").replace("/build/web/", "") + "/web/resources/fileupload/"+gen;
//            String path = getAppDomain() + "/resources/fileupload/" + gen;
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
//            File savedFile = new File(f.getAbsolutePath() + File.separator + fis.getName());
            String returnPath = "/resources/fileupload/"+gen+"/"+uploadFile.getFileName();
            File savedFile = new File(path + File.separator + uploadFile.getFileName());
            InputStream is = uploadFile.getInputstream();
            fos = new FileOutputStream(savedFile);
            int x = 0;
            byte[] b = new byte[1024];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.flush();
            fos.close();
//            return savedFile.getAbsolutePath();
            return  returnPath;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
            return "fail";
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(FileUpload.class.getName()).log(Level.SEVERE, null, ex);
                return "fail";
            }
        }
    }

    public FileUpload() {
        app_domain = getAppDomain();
    }
}
